<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

// 创建路由实例
const router = useRouter()

// 总记录数
// 选中的电影ID
const selectedMovieId = ref(null);


const total = ref(0)

// 分页参数
const pagination = ref({
  pageSize: 10,
  pageNum: 1
})

// 电影数据
const movies = ref([]);

// 票房数据
const boxOffice = ref([]);

// 影厅类型数据
const hallTypes = ref([]);

// 影厅数据
const venues = ref([]);

// 放映时间数据
const showTimes = ref([
  { id: 1, date: '今天 08月01日' },
  { id: 2, date: '明天 08月02日' },
  { id: 3, date: '后天 08月03日' },
  { id: 4, date: '周四 08月04日' },
  { id: 5, date: '周五 08月05日' },
]);

// 场次数据
const sessions = ref([]);
const activeHallTab = ref('');
const selectedShowTime = ref('');

// 搜索表单
const searchForm = ref({
  movieName: '',
  hallType: '',
  startTime: ''
});

// 监听影厅类型变化
watch(() => activeHallTab.value, (newVal) => {
  // 找到选中的影厅类型对应的id
  const selectedHall = hallTypes.value.find(hall => hall.name === newVal);
  searchForm.value.hallType = selectedHall ? selectedHall.id : '';
  // 重置分页并重新获取场次数据
  pagination.value.pageNum = 1;
  getSessions();
});

// 监听开场时间变化
watch(() => selectedShowTime.value, (newVal) => {
  if (newVal) {
    // 提取日期部分（去掉"今天"、"明天"、"后天"或星期几等前缀）
    const datePart = newVal.replace(/^[今天明天后天周一至周日]+/, '').trim();
    // 转换为标准日期格式（假设当前年份）
    const currentYear = new Date().getFullYear();
    const standardDate = `${currentYear}-${datePart.replace('月', '-').replace('日', '')}`;
    searchForm.value.startTime = standardDate;
  } else {
    searchForm.value.startTime = '';
  }
  // 重置分页并重新获取场次数据
  pagination.value.pageNum = 1;
  getSessions();
});

const handleSelect = (index, row) => {
  console.log('选座:', index, row);
};

// 处理电影海报点击事件
const handleMovieClick = (movie) => {
  // 设置选中的电影ID和名称
  selectedMovieId.value = movie.id;
  searchForm.value.movieName = movie.title;
  
  // 重置分页并重新获取场次数据
  pagination.value.pageNum = 1;
  getSessions();
};

//处理查看详情
const detailMovieClick = (movie) => {
  router.push({ path: `/movie-detail/${movie.id}` });
}

// 获取电影数据
const getMovies = async () => {
  try {
    
    const movieResponse = await axios.get('http://db.etoak.com:9527/seat/selectAllMovie');
    if (movieResponse.data.flag) {
      // 格式化电影数据
      movies.value = movieResponse.data.data.map(movie => ({
        id: movie.id,
        title: movie.name,
        poster: movie.posters.replace(/`/g, ''), // 移除海报URL中的反引号
        description: movie.synopsis,
        longTime: movie.longTime,
        boxOffice: movie.boxOffice
      }));

      // 格式化票房数据并按票房排序
      boxOffice.value = movieResponse.data.data
        .map(movie => ({
          rank: 0, // 临时占位，后面会设置
          movie: movie.name,
          amount: movie.boxOffice
        }))
        .sort((a, b) => b.amount - a.amount)
        .map((item, index) => ({
          ...item,
          rank: index + 1
        }));
    } else {
      console.error('获取电影数据失败:', movieResponse.data.msg);
    }
  } catch (error) {}
}  

//获取影厅类型数据
const getHallTypes = async () => { 
  try {
    const response = await axios.get('http://db.etoak.com:9527/seat/selectVenueType');
    if (response.data.flag) {
      hallTypes.value = response.data.data;
    } else {
      console.error('获取影厅类型数据失败:', response.data.msg);
    }
  } catch (error) {
    console.error('请求影厅类型接口失败:', error);
  }
}

//获取影厅数据
const getVenues = async () => {
  try { 
    const venueResponse = await axios.get('http://db.etoak.com:9527/seat/selectAllVenue');
    if (venueResponse.data.flag) {
      venues.value = venueResponse.data.data;
    } else {
      console.error('获取影厅数据失败:', venueResponse.data.msg);
    }
  } catch (error) {}
}

// 获取电影场次数据
const getSessions = async () => {
  try {
    // 显示加载状态
    console.log('正在加载电影场次数据...');
    
    const params = {
      pageSize: pagination.value.pageSize,
      pageNum: pagination.value.pageNum,
      movieName: searchForm.value.movieName,
      typeId: searchForm.value.hallType || undefined,
      startTime: searchForm.value.startTime || undefined
    }

    console.log('筛选参数:', params);

    const response = await axios.post('http://db.etoak.com:9527/seat/pageMovie', params)
    if (response.data.flag) {
      total.value = response.data.data.total
      sessions.value = response.data.data.scenesList.map(session => ({
        id: session.id,
        hall: session.venueName,
        movie: session.movieName,
        type: session.typeName,
        time: session.startTime,
        price: session.money,
        duration: session.longTime,
        capacity: session.x * session.y,
        ticketsLeft: (session.x * session.y) - (session.sale || 0)
      }))
      console.log('加载成功，共', total.value, '场电影');
    } else {
      console.error('获取电影场次失败:', response.data.msg)
      sessions.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('请求电影场次接口失败:', error)
    sessions.value = [];
    total.value = 0;
  }
}

// 分页变更
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  getSessions()
}
// 当前页变更
const handleCurrentChange = (current) => {
  pagination.value.pageNum = current
  getSessions()
}

// 初始加载数据
onMounted(
  async () => {
    await getMovies();
    await getHallTypes();
    await getVenues();

    // 设置默认选中的影厅类型和时间
    await getSessions();
  }
);

</script>

<template>
  <div class="movie-ticket-page">
    <!-- 顶部导航栏 -->
    <el-header style="background-color: #2c3e50; color: white;">
      <div class="tille" style="display: flex; justify-content: space-between; align-items: center; height: 100%;">
        <img src="" alt="Logo" style="height: 30px;" />
        <div style="display: flex; gap: 20px;">
          <router-link to="/home" custom v-slot="{ navigate, isActive }">
            <span
              @click="navigate"
              role="link"
              :class="{'active': isActive}"
              style="color: white; cursor: pointer;"
            >
              购票首页
            </span>
          </router-link>
          <router-link to="/movie-sessions-management" custom v-slot="{ navigate, isActive }">
            <span
              @click="navigate"
              role="link"
              :class="{'active': isActive}"
              style="color: white; cursor: pointer;"
            >
              电影场次管理
            </span>
          </router-link>
        </div>
        <span style="color: white;">欢迎您回来 程皓祥</span>
      </div>
    </el-header>

    <!-- 主体内容 -->
     <el-main>
      <div class="content" style="display: flex;">
        <!-- 左侧内容 - Main Content -->
        <div class="main-content" style="width: 80%; margin-right: 20px;">
          <!-- 电影海报区域 -->
          <div class="movie-posters" style="height: 400px">
            <el-row :gutter="20">
              <el-col :span="4" v-for="movie in movies" :key="movie.id" style="margin-bottom: 20px;">
                <el-card :body-style="{ padding: '0px' }" :class="selectedMovieId === movie.id ? 'selected-movie' : ''" style="background-color: #f9fafc; transition: all 0.3s ease;" @click="handleMovieClick(movie)">
                  <img :src="movie.poster" class="image" :class="selectedMovieId === movie.id ? 'selected-image' : ''" style="width: 100%; height: 250px; object-fit: cover; border-radius: 4px; transition: all 0.3s ease;" />
                  <div style="padding: 14px; text-align: center;">
                    <span class="movie-title">{{ movie.title }}</span>
                    <div class="bottom" style="margin-top: 10px;">
                      <el-button type="text" class="button" style="color: #409EFF;" @click="detailMovieClick(movie)">查看详情</el-button>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>

          <!-- 影厅类型和开场时间选择 -->
          <div class="hall-time-selector">
            <div style="margin-bottom: 10px; font-weight: bold; font-size: 16px;">影厅类型</div>
            <div style="display: flex; align-items: center; gap: 10px; margin: 10px 0 20px 0; flex-wrap: wrap;">
              <el-radio-group v-model="activeHallTab" style="display: flex; gap: 10px; flex-wrap: wrap;">
                <el-radio-button v-for="hall in hallTypes" :key="hall.id" :label="hall.name" style="background-color: #f5f7fa; border-color: #dcdfe6;"></el-radio-button>
              </el-radio-group>
              <el-button style="margin-left: 30px; background-color: gray; opacity: 0.7; color: white;" type="default" size="medium" @click="activeHallTab = ''; searchForm.hallType = ''; pagination.pageNum = 1; getSessions()">重置</el-button>
            </div>

            <!-- 开场时间选择 - 移到影厅类型标签下方，始终显示 -->
            <div style="margin-bottom: 10px; font-weight: bold; font-size: 16px;">开场时间</div>
            <div style="display: flex; align-items: center; gap: 10px; margin: 10px 0; flex-wrap: wrap;">
              <el-radio-group v-model="selectedShowTime" style="display: flex; gap: 10px; flex-wrap: wrap;">
                <el-radio-button v-for="time in showTimes" :key="time.id" :label="time.date" style="background-color: #f5f7fa; border-color: #dcdfe6;"></el-radio-button>
              </el-radio-group>
              <el-button style="margin-left: 30px; background-color: gray; opacity: 0.7; color: white;" type="default" size="medium" @click="selectedShowTime = ''; searchForm.startTime = ''; pagination.pageNum = 1; getSessions()">重置</el-button>
            </div>
          </div>

          <!-- 场次列表 -->
          <div class="session-list">
            <el-table :data="sessions" border style="width: 100%; margin-top: 20px; border-collapse: separate; border-spacing: 0 10px;">
              <el-table-column label="场次列表" width="150">
                <template #default>
                  <span style="color: #F56C6C">场次列表</span>
                </template>
              </el-table-column>
              <el-table-column label="电影厅" width="200">
                <template #default="scope">
                  <div>{{ scope.row.hall }}</div>
                  <div style="font-size: 12px; color: #909399;">{{ scope.row.movie }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="time" label="电影开场时间" width="200"></el-table-column>
              <el-table-column prop="ticketsLeft" label="剩余票数" width="200"></el-table-column>
              <el-table-column prop="price" label="票价" width="200">
                <template #default="scope">
                  <span style="color: #F56C6C;">¥{{ scope.row.price }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="scope">
                  <el-button size="mini" type="primary" @click="handleSelect(scope.$index, scope.row)" :disabled="scope.row.ticketsLeft === 0">选座</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 分页 -->
          <div style="text-align: right; margin-top: 10px;">
            <el-pagination
              small
              layout="total, prev, pager, next"
              :total="total"
              :page-size="pagination.pageSize"
              :current-page="pagination.pageNum"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            ></el-pagination>
          </div>

        </div>

        <!-- 右侧内容 - 票房榜 -->
        <div class="box-office" style="width: 30%">
          <div style="background-color: #f9fafc; padding: 20px; border: 1px solid #ebeef5;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
              <h3 style="margin: 0; color: #303133;">票房榜(总金额)</h3>
              <div style="color: #F56C6C; display: flex; align-items: center;">
                <span>143072</span>
                <span style="font-size: 12px; margin-left: 5px;">万</span>
                <span style="margin-left: 5px;">↑</span>
              </div>
            </div>
            <ul style="list-style: none; padding: 0;">
              <li v-for="item in boxOffice" :key="item.rank" style="display: flex; justify-content: space-between; margin-bottom: 12px; align-items: center;">
                <span :style="{ color: item.rank <= 3 ? '#F56C6C' : '#909399', fontWeight: item.rank <= 3 ? 'bold' : 'normal' }">{{ item.rank }}</span>
                <span style="flex: 1; margin: 0 10px; color: #606266; text-align: left;">{{ item.movie }}</span>
                <span style="color: #606266;">{{ item.amount }}万</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </el-main>
  </div>


</template>

<style scoped>
/* 电影选票 */
.movie-ticket-page {
  font-family: Arial, sans-serif;
}

.movie-posters .image {
  width: 100%;
  height: 250px;
  object-fit: cover;
  display: block;
  border-radius: 4px;
}

.movie-title {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  height: 42px;
  font-size: 16px;
  font-weight: bold;
  line-height: 1.4;
}

/* 选中电影海报的样式 */
.selected-movie {
  transform: translateY(-10px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
  border: 3px solid gray;
  z-index: 10;
}

.selected-image {
  transform: scale(1.05);
  border-radius: 8px;
}

/* 添加脉冲动画效果 */
@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(64, 158, 255, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0);
  }
}

.selected-movie::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-radius: inherit;
  animation: pulse 1.5s infinite;
  z-index: -1;
}

.el-table th,.el-table td {
  text-align: center !important;
  padding: 12px 15px !important;
}

.el-table .cell {
  white-space: nowrap;
}

/* 增加表格行间距 */
.el-table__body tr {
  margin-bottom: 10px !important;
}

/* 调整表头样式 */
.el-table__header th {
  background-color: #f5f7fa !important;
  font-weight: bold !important;
}

.el-button--primary {
  background-color: #409EFF;
  border-color: #409EFF;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.el-button--text {
  color: #409EFF;
}

.el-button--text:hover {
  color: #66b1ff;
}

/* 新增样式 */
.main-content {
  display: flex;
  flex-direction: column;
}

.box-office {
  width: 100%;
}

.tille {
  display: flex;
  justify-content: center; /* 居中对齐 */
}
</style>